package com.example.content_android.ui.home;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.content_android.R;
import com.nostra13.universalimageloader.utils.L;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AnnouncementFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AnnouncementFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AnnouncementFragment extends Fragment implements AdapterView.OnItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    ListView listView;
    SimpleAdapter simpleAdapter;

    public List<Map<String, Object>> list = new ArrayList<>();
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public AnnouncementFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AnnouncementFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AnnouncementFragment newInstance(String param1, String param2) {
        AnnouncementFragment fragment = new AnnouncementFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try {
            initData();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initData() throws IOException {
        Response response = OkHttpUtils
                .get()//
                .url("https://www.turkeylike.cn:8900/fzulab/article/list")//
                .addParams("limit","10")
                .addParams("columnId","3")
                .tag(this)//
                .build()//
                .execute();

        JSONObject jsonObject = JSONObject.parseObject(response.body().string());

        if (jsonObject.getInteger("code") == 500) {
            String msg = jsonObject.getString("msg");

            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            return;

        }
        if (jsonObject.getInteger("code") == 0) {
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray fileArray = result.getJSONArray("list");


            if (fileArray != null && fileArray.size() > 0) {
                for (int i = 0; i < fileArray.size(); i++) {
                    JSONObject str = JSON.parseObject(fileArray.get(i).toString());

                    Map map = new HashMap();
                    map.put("home_announcement_title", str.get("title").toString());
                    map.put("home_announcement_date", str.get("createDate").toString());


                    list.add(map);
                }
            }

        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view =inflater.inflate(R.layout.fragment_home_announcement_list,container,false);
        listView =view.findViewById(R.id.home_announcement_list_view);

        simpleAdapter = new SimpleAdapter(getActivity(),getData(),R.layout.home_annouoncement_list_item,new String[]{"home_announcement_title","home_announcement_date"},new int[]{R.id.home_announcement_title,R.id.home_announcement_date});
        listView.setAdapter(simpleAdapter);

        listView.setOnItemClickListener(this);
        return view;



        // Inflate the layout for this fragment

    }



    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    private List<Map<String,Object>> getData() {
//        String [] titles={"水果1","水果2"};
//        int [] images={R.drawable.addactive,R.drawable.downloadsactive};
//        List<Map<String,Object>> list= new ArrayList<>();
//        for(int i=0;i<2;i++){
//            Map  map = new HashMap();
//            map.put("title",titles[i]);
//            map.put("image",images[i]);
//            list.add(map);
//        }
        return list;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        L.i("position:"+position);
        String text = listView.getAdapter().getItem(position).toString();
        L.i("position:"+position+"text"+text );
    }
}
